#include<func.h>

//共享结构体
typedef struct Share_s
{
    //条件
    int flags;
    //锁
    pthread_mutex_t mutex;
    //条件变量
    pthread_cond_t cond;
}Share_t;

//线程1
void*pthreadFunc1(void *args)
{
    Share_t *share = (Share_t*)args;
    
    while(1)
    {
        //printf("pth is open\n");
        pthread_mutex_lock(&share->mutex);
        if(share->flags != 1)
        {
            //如果没有就继续等
            pthread_cond_wait(&share->cond,&share->mutex);
        }
        
        //执行B事件
        printf("this is B\n");
        pthread_mutex_unlock(&share->mutex);
        //解锁再发信号
        //发送信号给主线程
        //再次进行访问数据
        pthread_mutex_lock(&share->mutex);
        //修改flags
        share->flags++; //flags ==2 ;
        pthread_cond_signal(&share->cond);
        pthread_mutex_unlock(&share->mutex);
        
        //printf("pth is over\n");
        //退出
        pthread_exit(NULL);
    }

}

int main(void)
{
    //主线程是线程A
    //初始化变量
    Share_t share;
    //初始化锁
    pthread_mutex_init(&share.mutex,NULL);
    //初始化条件变量
    pthread_cond_init(&share.cond,NULL);
    //初始化flags
    share.flags =0;
    pthread_t td1;
    pthread_create(&td1,NULL,pthreadFunc1,&share);
    //执行A事件
    printf("this is A\n");
    pthread_mutex_lock(&share.mutex);
    share.flags++; //flags 此时等于1
    pthread_mutex_unlock(&share.mutex);
    pthread_cond_signal(&share.cond); //发送信号
    //创建子线程

    //C事件
    while(1)
    {
        //sleep(3);
        pthread_mutex_lock(&share.mutex);
        if(share.flags != 2)
        {
            //如果没有就继续等
            pthread_cond_wait(&share.cond,&share.mutex);
        }
        //执行完事件再解锁
        printf("this is C\n");
        pthread_mutex_unlock(&share.mutex);
        return 0;
    }
}